function applymiddleware(...middlewares) {
    return function (createStore) {
        return function (reducer) {
            const store = createStore(reducer)
            let dispatch = store.dispatch
            const middleAPI = {
                dispatch: (action, ...args) => dispatch(action, args),
                getState: store.getState
            }
            const chain = middlewares.map(middleware => middleware(middleAPI))
            // 从右向左，最开始的参数为store.dispatch, A(B(C(store.dispatch)))
            dispatch = compose(...chain)(store.dispatch)
            return {
                ...store,
                dispatch
            }
        }
    }
}


function compose(...funcs) {
    if (funcs.length === 0) {
        return (args) => args
    }
    if (funcs.length === 1) {
        return funcs[0]
    }
    return funcs.reduce((a, b) => {
        return (...args) => {
            return a(b(...args))
        }
    })
}

function createThunkMiddleware(extraArg) {
    return ({dispatch, getState}) => {
        return next => {
            return action => {
                if (typeof action === 'function') {
                    return action(dispatch, getState, extraArg)
                }
                return next(action)
            }
        }
    }
}